<template>
  <a-layout class="role-list-wrap">
    <a-layout-sider style="width: auto; min-width: 280px">
      <div class="flex-c">
        <a-input-search v-model="searchRoleVal" placeholder="角色名称" allow-clear @search="getRoleList" @press-enter="getRoleList" />
        <a-button class="gray-outline ml10" @click="showAddRole('add')">添加角色</a-button>
      </div>
      <a-scrollbar style="height: calc(100vh - 170px); overflow: auto">
        <ul class="role-list">
          <li v-for="(role, i) in roleList" :key="i" :class="{ active: activeRoleId == role.id }" class="clearfix role-item" @click="changeRole(role)">
            <div class="fl">
              <div>{{ role.roleName }}（{{ role.roleCode }}）</div>
              <div class="time-text">{{ $setTime(role.gmtCreate, 'YYYY-MM-DD HH:ss') }}</div>
            </div>
            <div class="fr setting" style="padding: 10px">
              <icon-edit class="highlight cursor" @click.stop="showAddRole('edit', role)" />
              <icon-delete class="ml10 highlight cursor" @click.stop="del(role.id)" />
            </div>
          </li>
        </ul>
      </a-scrollbar>
    </a-layout-sider>
    <a-layout class="role-user-w table-gl-w">
      <div class="sel-item">
        <div class="name">{{ data.curRoleInfo.roleName }}（{{ data.curRoleInfo.roleCode }}）</div>
        <div class="desc mt10" style="color: #7f7f7f" v-if="data.curRoleInfo.description">{{ data.curRoleInfo.description || '这是一段测试文字' }}</div>
        <div class="time-other-info mt10" style="color: #7f7f7f">
          <span class="mr10">添加人：{{ data.curRoleInfo.createUname }}</span>
          <span class="mr10">添加时间：{{ $setTime(data.curRoleInfo.gmtCreate) }}</span>
          <span class="mr10">更新人：{{ data.curRoleInfo.updateUname }}</span>
          <span class="mr10">更新时间：{{ $setTime(data.curRoleInfo.gmtWrite) }}</span>
        </div>
      </div>

      <a-tabs v-model:active-key="data.currentPage" @change="changeTab">
        <a-tab-pane key="1" title="授权成员" />
        <a-tab-pane key="2" title="授权部门" />
        <a-tab-pane key="3" title="功能权限" />
      </a-tabs>
      <div class="table-gl-con">
        <template v-if="data.currentPage == '1'">
          <TableWrap style="flex: 1" @refresh="getUserByRole">
            <template #headerLeft>
              <a-space>
                <FilterTable :isShowTag="false" :filterItem="filterItem" @search="searchByVal" />
                <a-button type="primary" size="medium" @click="showChooseUserDialog = true">添加用户</a-button>
                <a-button class="gray-outline" @click="removeUser(selectRow)">批量移除</a-button>
              </a-space>
            </template>
            <template #tableBody>
              <a-table
                class="table-singe-line show-border-table"
                :scroll="{
                  y: '100%',
                }"
                ref="tableRef"
                :loading="tableLoading"
                @selection-change="selectColumn"
                :row-selection="rowSelection"
                row-key="id"
                :columns="tableColumns"
                :data="userList"
                size="mini"
                :pagination="false"
              >
                <template #columns>
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.title === '操作'" #cell="{ record }">
                      <a-space>
                        <a-button type="text" size="mini" @click="removeUser([record.id])">移除</a-button>
                      </a-space>
                    </template>
                    <template v-else #cell="{ record }">
                      {{ record[item.dataIndex] }}
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </TableWrap>
        </template>
        <DeptRole v-if="data.currentPage == '2'" ref="deptRoleRef" :roleId="activeRoleId" />
        <Permission v-if="data.currentPage == '3'" ref="permission" :roleId="activeRoleId" />
      </div>
    </a-layout>
  </a-layout>
  <ChooseUser v-if="showChooseUserDialog" :multiple="true" :isShow="showChooseUserDialog" :isRequired="true" @closed="showChooseUserDialog = false" @success="bindUser" />
  <AddRole ref="addRole" :type="data.addRoleType" :info="data.addRoleInfo" @save="getRoleList" />
</template>
<script lang="ts" setup>
  import { defineComponent, ref, reactive, onMounted } from 'vue'
  import TableWrap from '@/components/TableWrap.vue'
  import ChooseUser from '@/components/ChooseUser.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import AddRole from './components/addRole.vue'
  import Permission from './components/permission.vue'
  import DeptRole from './components/deptRole.vue'
  import { findRoleListByParam, getUserByRole, roleUnbindUser, roleBindUser, deleteRole } from '@/api/system'
  import { nextTick } from 'vue'

  onMounted(async () => {
    await getRoleList()
    changeRole(roleList.value?.[0])
  })
  const tableColumns: Array<any> = [
    {
      title: '用户名',
      dataIndex: 'loginName',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '工号',
      dataIndex: 'employeeNumber',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 80,
    },
  ]
  const filterItem: any = ref([
    {
      key: 'keywords',
      label: '用户名或姓名',
      value: ref(),
      type: 'input_search',
      width: 260,
    },
  ])

  const data: any = reactive({
    addRoleType: '',
    addRoleInfo: {},
    currentPage: '1',
    curRoleInfo: {},
  })

  const addRole = ref()
  const permission = ref()
  const deptRoleRef = ref()
  const searchRoleVal = ref('')
  const roleList = ref<any>([]) //角色列表
  const activeRoleId = ref('') //当前角色code
  const userList = ref<Array<any>>([]) //用户列表
  const tableLoading = ref(false)
  const tableRef = ref()
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const selectRow = ref([]) //选中数据
  const showChooseUserDialog = ref(false)
  const filterData = ref<any>({})
  // 选中数据
  function selectColumn(val: any) {
    selectRow.value = val
  }
  // 获取角色列表
  async function getRoleList() {
    const res: any = await findRoleListByParam({ roleName: searchRoleVal.value })
    roleList.value = res?.data || []
    // activeRoleId.value = res.data[0].id
    // data.curRoleInfo = res.data[0] || {}
    // if (data.currentPage == '1') {
    //   getUserListByRole()
    // }
    // if (data.currentPage == '3') {
    //   // 获取角色下面的功能权限（调用permission组件下面的方法）
    //   permission.value.getPermissionTreeList()
    // }
  }
  // 获取当前角色下的用户列表
  async function getUserListByRole() {
    tableLoading.value = true
    const res: any = await getUserByRole({
      roleId: activeRoleId.value,
      pageNum: 1,
      pageSize: 1000,
      ...filterData.value,
    }).catch(() => false)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    userList.value = res?.data?.records || []
  }
  // 点击角色获取列表
  function changeRole(role: any) {
    if (!role?.id) return
    if (activeRoleId.value == role.id) return
    data.curRoleInfo = role
    activeRoleId.value = role.id
    nextTick(() => {
      if (data.currentPage == '1') {
        getUserListByRole()
      }
      if (data.currentPage == '2') {
        // 获取角色下面的授权部门
        deptRoleRef.value.getDeptListByRole()
      }
      if (data.currentPage == '3') {
        // 获取角色下面的功能权限（调用permission组件下面的方法）
        permission.value.getPermissionTreeList()
      }
    })
  }

  function changeTab() {
    if (data.currentPage == '1') {
      getUserListByRole()
    }
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    filterData.value = info
    getUserListByRole()
  }
  // 移除用户
  function removeUser(ids: any) {
    if (!ids?.length) {
      return Message.error('请选择需要操作的数据')
    }
    Modal.error({
      title: '移除确认',
      content: '请再次确认，把选中用户从该权限中移除？',
      titleAlign: 'start',
      hideCancel: false,
      async onBeforeOk(done) {
        const res: any = await roleUnbindUser({
          id: activeRoleId.value,
          userIds: ids,
        })
        getUserListByRole()
        done(true)
      },
    })
  }
  // 绑定用户
  async function bindUser(users: any) {
    const res: any = await roleBindUser({
      id: activeRoleId.value,
      userIds: users,
    })
    if (res) {
      Message.success('添加成功')
      getUserListByRole()
    }
  }

  const showAddRole = (type: string, item?: any) => {
    data.addRoleType = type
    data.addRoleInfo = item
    addRole.value.visible = true
  }

  const del = (id: string) => {
    Modal.error({
      title: '提示',
      content: '是否删除角色？',
      titleAlign: 'start',
      hideCancel: false,
      onOk: async () => {
        const res: any = await deleteRole({
          idList: [id],
        })
        getRoleList()
      },
    })
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'RoleList',
  })
</script>
<style lang="less" scoped>
  .role-list-wrap {
    height: calc(100vh - @menuHeight);
    padding: 5px;
    box-sizing: border-box;
    :deep(.filter-item) {
      margin: 0 !important;
    }
    .arco-layout-sider {
      padding: 10px;
    }
    .arco-scrollbar {
      margin-top: 20px;
    }
    .role-list {
      .setting {
        display: none;
      }

      .role-item {
        &:hover {
          .setting {
            display: block;
          }
        }
      }

      li {
        .fl {
          padding: 2px;
        }
        background-color: var(--color-neutral-1);

        margin-bottom: 5px;
        &:hover {
          background-color: var(--color-neutral-3);
        }
        &.active {
          background-color: var(--color-neutral-3);
        }
      }
    }
    .role-user-w {
      background-color: #fff;
      margin-left: 5px;
      height: auto;
      .search-w {
        padding: 10px 10px 0;
      }
      // .role-con {
      //   flex: 1;
      //   overflow: hidden;
      //   display: flex;
      //   height: auto;
      //   flex-direction: column;
      // }
    }
    :deep(.arco-tabs-content) {
      padding: 0;
    }
    .line {
      height: 5px;
      width: 100%;
      background-color: #f0f2f5;
    }

    .sel-item {
      padding: 10px 10px 0;
    }
  }
</style>
